$(document).ready(function () {
    // 检查路径匹配
    const currentPath = location.href;
    console.log("当前路径:", currentPath);

    // 创建交互弹出层
    $("body").append(`
                <div id="audioPermissionModal" style="
                    position: fixed;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    background: white;
                    padding: 20px;
                    border-radius: 8px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    z-index: 9999;
                    text-align: center;
                    display: none;
                ">
                    <h3>订单提醒</h3>
                    <p>请点击确认开启订单语音提醒</p>
                    <button id="enableAudio" style="
                        padding: 8px 20px;
                        background: #007bff;
                        color: white;
                        border: none;
                        border-radius: 4px;
                        cursor: pointer;
                    ">确认</button>
                </div>
            `);

    // 检查是否在指定路径且有appid
    if (
        new URLSearchParams(window.location.search).has("appid") ||
        new URLSearchParams(location.hash.split("?")[1] || "").has("appid")
    ) {
        let appid =
            new URLSearchParams(window.location.search).get("appid") ||
            new URLSearchParams(location.hash.split("?")[1] || "").get("appid");

        let lastOrderSn = localStorage.getItem("lastOrderSn") || "";
        const localAudio = new Audio("/extend/notice.mp3");
        let audioPlayPromise;
        let audioPlayCount = parseInt(
            localStorage.getItem("audioPlayCount") || "0"
        );
        const MAX_AUDIO_PLAYS = 15;

        // 检查浏览器是否支持自动播放
        async function checkAutoplaySupport() {
            try {
                audioPlayPromise = await localAudio.play();
                localAudio.pause();
                return true;
            } catch (err) {
                console.log("自动播放不支持，显示交互弹窗:", err);
                $("#audioPermissionModal").show();

                // 添加确认按钮点击事件
                $("#enableAudio").one("click", function () {
                    localStorage.setItem("audioPlayCount", 0);
                    audioPlayPromise = localAudio
                        .play()
                        .then(() => {
                            localAudio.pause();
                            $("#audioPermissionModal").hide();
                        })
                        .catch((err) => console.log("音频播放失败:", err));
                });
                return false;
            }
        }

        checkAutoplaySupport();

        // 创建订单提醒DOM
        $("body").append(
            `<a href="/app/ycMassage/admin/#/Orders/index?type=reservation&appid=${appid}"  id="orderNotification" style="position: fixed; bottom: 10px; right: 20px; background: #ff4444; color: white; padding: 10px; border-radius: 5px; display: none;"></a>`
        );
        console.log("路径匹配成功，开始执行主逻辑");
        // 定时查询订单
        setInterval(function () {
            console.log("查询订单");
            $.ajax({
                url: "/app/ycMassage/admin/Index/orders",
                data: {
                    appid: appid,
                },
                method: "GET",
                dataType: "json",
                headers: {
                    Appid: appid,
                    Authorization:
                        localStorage.getItem("admin_authorization") || "", // 从localStorage获取authorization
                },
                success: function (response) {
                    if (response.data.orders_num > 0) {
                        $("#orderNotification")
                            .html(
                                `等待服务未开始数：${response.data.orders_num} 笔`
                            )
                            .show();

                        // 修改播放逻辑
                        if (audioPlayPromise !== undefined) {
                            if (lastOrderSn !== response.data.last_order) {
                                // 重置播放计数并更新 localStorage
                                audioPlayCount = 0;
                                localStorage.setItem(
                                    "audioPlayCount",
                                    audioPlayCount
                                );
                                localStorage.setItem(
                                    "lastOrderSn",
                                    response.data.last_order
                                );
                            }

                            if (audioPlayCount < MAX_AUDIO_PLAYS) {
                                localAudio
                                    .play()
                                    .catch((err) =>
                                        console.log("音频播放失败:", err)
                                    );
                                audioPlayCount++;
                                localStorage.setItem(
                                    "audioPlayCount",
                                    audioPlayCount
                                );
                            }
                        }

                        if (response.data.last_order) {
                            lastOrderSn = response.data.last_order;
                        }
                    } else {
                        $("#orderNotification").hide();
                    }
                },
            });
        }, 3000); // 每30秒查询一次
    } else {
        console.log("路径不匹配，当前路径:", location.href);
    }
});
